/**
 * Created by Administrator on 2016/5/27.
 */

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.mugen.Mugen;
import com.mugen.MugenCallbacks;
import com.mugen.attachers.BaseAttacher;

import org.xmlpull.v1.XmlPullParserException;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class BlogListFragment extends Fragment {
    private View mView;
    //下拉刷新
    private SwipeRefreshLayout mRefreshLayout;
    //无限滚动
    private BaseAttacher mBaseAttacher;

    private MyProgressBar myProgressBar;
    private RecyclerView mRecyclerView;
    private BlogListAdapter mBlogListAdapter;

    //数据源
    private List<Blog> mBlogs;

    //是否正在加载
    private boolean isLoading = false;
    //当前页数
    private int currentPage = 1;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_bloglist, null);
        initView();
        initData();
        initAction();
        return mView;
    }

    /**
     * 初始化控件监听
     */
    private void initAction() {
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData(1, 20);
            }
        });
        //设置无限滚动，上拉加载
        mBaseAttacher = Mugen.with(mRecyclerView, new MugenCallbacks() {
            @Override
            public void onLoadMore() {
                //加载更多
                isLoading = true;
                myProgressBar.setVisibility(View.VISIBLE);
                getData((currentPage + 1), 20);
            }

            @Override
            public boolean isLoading() {
                return isLoading;
            }

            @Override
            public boolean hasLoadedAllItems() {
                return false;
            }
        }).start();


    }

    /**
     * 初始化数据
     */
    private void initData() {
        mBlogs = new ArrayList<Blog>();
        //设置空数据给RecyclerView
        mBlogListAdapter = new BlogListAdapter(getActivity(), mBlogs);
        mRecyclerView.setAdapter(mBlogListAdapter);
        //显示下拉刷新样式
        mRefreshLayout.setRefreshing(true);
        //刚开始加载20条数据
        getData(1, 20);

    }


    /**
     * 初始化控件
     */

    private void initView() {
        mRefreshLayout = (SwipeRefreshLayout) mView.findViewById(R.id.swipe_refresh);
        mRecyclerView = (RecyclerView) mView.findViewById(R.id.rv_view);
        myProgressBar = (MyProgressBar) mView.findViewById(R.id.progressbar);

        //设置拉下刷新滚动条颜色
        mRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
        //设置RecyclerView显示样式
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    }

    public void getData(final int page, int num) {
        //更新当前页数
        this.currentPage = page;
        String url = "http://wcf.open.cnblogs.com/blog/sitehome/paged/" + page + "/" + num;
        StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    isLoading = false;
                    myProgressBar.setVisibility(View.GONE);
                    ByteArrayInputStream inputStream = new ByteArrayInputStream(s.getBytes());
                    //获取List数据集合
                    List<Blog> blogs = BlogsListXmlParser.getListBlogs(inputStream, "utf-8");
                    if (page == 1) {
                        //清空之前的数据预防重复加载
                        mBlogs.clear();
                    }
                    for (Blog blog : blogs) {
                        //整理数据源
                        mBlogs.add(blog);
                    }

                    if (mBlogListAdapter == null) {
                        //如果Adapter不存在
                        mBlogListAdapter = new BlogListAdapter(getActivity(), mBlogs);
                        mRecyclerView.setAdapter(mBlogListAdapter);
                    } else {
                        //存在通知adatper数据源更新
                        mBlogListAdapter.refreshData(mBlogs);
                    }


                    //关闭下拉刷新样式
                    mRefreshLayout.setRefreshing(false);

                } catch (XmlPullParserException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(getActivity(), volleyError.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

        //加入Volley请求队列
        VolleyRequestQueueManager.addRequest(request, "getBlogList");


    }
}
